package com.api.controller;


import com.api.annotation.Login;
import com.api.common.constant.Constant;
import com.api.common.exception.MySystemException;
import com.api.common.utils.ConvertUtils;
import com.api.common.utils.Result;
import com.api.entity.Item;
import com.api.entity.StarCollect;
import com.api.entity.dto.ItemDTO;
import com.api.service.IStarCollectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 点赞收藏表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-13
 */
@RestController
@RequestMapping("/api/behavior")
@AllArgsConstructor
public class StarCollectController {
    private  final IStarCollectService iStarCollectService;


    @Login
    @PostMapping("{id}")
    @Operation(summary = "用户收藏")
    public Result getCollect(@PathVariable("id") Long id,@RequestAttribute("userId") Long userId) {
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        lwq.eq(StarCollect::getUserId,userId);
        lwq.eq(StarCollect::getItemId,id);
        lwq.eq(StarCollect::getType, Constant.COLLECT);
        if(iStarCollectService.exists(lwq)){
            throw  new MySystemException("您已经收藏！");
        }
        StarCollect collect = new StarCollect();
        collect.setType(Constant.COLLECT);
        collect.setUserId(userId);
        collect.setItemId(id);
        iStarCollectService.save(collect);
        return new Result();
    }


    @Login
    @GetMapping("{id}")
    @Operation(summary = "查看是否收藏")
    public Result<Double> isCollect(@PathVariable("id") Long id,@RequestAttribute("userId") Long userId) {
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        lwq.eq(StarCollect::getUserId,userId);
        lwq.eq(StarCollect::getItemId,id);
        lwq.eq(StarCollect::getType, Constant.COLLECT);
        if(iStarCollectService.exists(lwq)){
            return new Result().ok(true);
        }
        return new Result().ok(false);
    }


    @Login
    @DeleteMapping("{id}")
    @Operation(summary = "取消收藏")
    public Result delCollect(@PathVariable("id") Long id,@RequestAttribute("userId") Long userId) {
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        lwq.eq(StarCollect::getUserId,userId);
        lwq.eq(StarCollect::getItemId,id);
        lwq.eq(StarCollect::getType, Constant.COLLECT);
        if(!iStarCollectService.exists(lwq)){
            throw  new MySystemException("您还没收藏，无需点击！");
        }
        StarCollect one = iStarCollectService.getOne(lwq);
        iStarCollectService.removeById(one.getId());
        return new Result();
    }



}
